#!/usr/bin/env python
import sys
import json
import socket


class Monitor(object):

    def __init__(self, path):
        self.path = path
        self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

    def connect(self):
        self.s.connect(self.path)
        self.recv()
        payload = {
            "execute": "qmp_capabilities"
        }
        self.send(payload)
        self.recv()

    def send(self, payload):
        self.s.send(json.dumps(payload))

    def recv(self):
        rsp = ""
        while 1:
            snip = self.s.recv(1024)
            rsp += snip
            if len(snip) < 1024:
                break
        return json.loads(rsp)

    def close(self):
        self.s.shutdown(2)
        self.s.close()


def set_boot_dev(working_dir, node_name, boot_order, boot_once):
    cmd = {
        "execute": "save-bootdev",
        "arguments": {
            "boot_order": boot_order,
            "boot_once": (int)(boot_once),
        }
    }
    path = working_dir + ("/.infrasim/{}/.monitor".format(node_name))
    monitor = Monitor(path)
    monitor.connect()
    monitor.send(cmd)
    monitor.recv().get("return")
    monitor.close()

if __name__ == "__main__":
    args = sys.argv[1:]
    working_dir = args[0]
    node_name = args[1]
    boot_order = args[2]
    boot_once = args[3]
    set_boot_dev(working_dir, node_name, boot_order, boot_once)
